package org.yylnb.openplatform.payment.controller;

import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yylnb.openplatform.commons.bean.PayMQBean;
import org.yylnb.openplatform.payment.mq.SendPaymentResultMQBean;
import org.yylnb.openplatform.payment.myInterface.PayConfig;
import org.yylnb.openplatform.payment.utlis.PayCommonUtil;
import org.yylnb.openplatform.payment.utlis.XMLUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author RainLin
 * @date 2020/7/28 - 20:35
 */
@RestController
public class PayMentResultController {
    @Autowired
    private SendPaymentResultMQBean sendPaymentResultMQBean;

    @RequestMapping("/paymentresult")
    public String getResult(HttpServletRequest request) throws IOException, JDOMException {
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        StringBuffer stringBuffer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        bufferedReader.close();

        // System.err.println(stringBuffer.toString());
        String result = stringBuffer.toString();
        System.err.println(result);
        Map map = XMLUtil.doXMLParse(result);//解析微信返回的结果
        TreeMap treeMap = new TreeMap(map);
        if (PayCommonUtil.isTenpaySign("UTF-8",treeMap, PayConfig.API_KEY)) {
            //代表我们校验了属于微信给我们返回的内容

            //给用户加钱,通知页面跳转
            //获取到当前支付的订单号所属页面的会话
            String out_trade_no = (String) map.get("out_trade_no");
//            WebSocketSession session = MyTextWebSocketHandler.getAllClients().get(out_trade_no);
//            if (session != null&&session.isOpen()) {
//                session.sendMessage(new TextMessage("1"));//给网页发送数据,我们约定发送1 跳转一个页面
//            }
            MessageChannel channel = sendPaymentResultMQBean.message_channel();
            PayMQBean payMQBea = new PayMQBean();
            payMQBea.setOid(out_trade_no);
            payMQBea.setCount(100);
            channel.send(new GenericMessage<PayMQBean>(payMQBea));//发送消息

            //给用户加钱 10.0.134.208

            String returnContent="<xml>" +
                    " <return_code><![CDATA[SUCCESS]]></return_code>" +
                    " <return_msg><![CDATA[OK]]></return_msg>" +
                    "</xml>";
            return returnContent;
        }

        return result;

    }
}

